<template>
	<div class="common-layout">
		<el-container style="height: 100vh">
			<!-- 头部 -->
			<el-header class="header">
				<div>学生宿舍管理系统</div>
				<!-- 下拉菜单 -->
				<!-- 头像 -->
				<div class="position">
					<el-dropdown>
						<span class="el-dropdown-link">
							<div class="demo-type">
								<div>
									<el-avatar> 陆 </el-avatar>
								</div>
							</div>
							<el-icon class="el-icon--right"><arrow-down /></el-icon>
						</span>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item command="a" @click="handleRegister"
									>注销</el-dropdown-item
								>
							</el-dropdown-menu>
							<el-dropdown-menu>
								<el-dropdown-item command="a" @click="handleChangePassword"
									>修改密码</el-dropdown-item
								>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</div>
			</el-header>
			<el-container>
				<!-- 侧边栏 -->
				<el-aside class="aside">
					<ul>
						<li>
							<router-link to="/index" class="a">首页</router-link>
						</li>
						<li>
							<router-link to="/studentmanage" class="a active"
								>学生管理</router-link
							>
						</li>
						<li>
							<router-link to="/dormitorymanage" class="a"
								>宿舍管理</router-link
							>
						</li>
						<li>
							<router-link to="/livemanage" class="a">入住管理</router-link>
						</li>
						<li>
							<router-link to="/floormanage" class="a">楼宇管理</router-link>
						</li>
					</ul>
				</el-aside>
				<el-container>
					<!-- 主体部分 -->
					<el-main style="background-color: #fff; text-align: center">
						<!-- 学生管理 -->
						<div
							style="
								border: 1px solid #fff;
								height: 70px;
								line-height: 70px;
								box-shadow: 1px 2px 10px #999;
							"
						>
							学生管理
							<el-input
								v-model="std"
								style="width: 240px; padding-left: 50px"
								placeholder="学生学号"
							/>
							<el-input
								v-model="studentName"
								style="width: 240px; padding-left: 50px"
								placeholder="学生姓名"
							/>
							<el-button
								type="success"
								style="margin-left: 50px"
								@click="search"
							>
								<el-icon>
									<Search />
								</el-icon>
								<span>查询</span>
							</el-button>

							<el-button type="primary" @click="addStudent = true">
								<el-icon>
									<CirclePlusFilled />
								</el-icon>
								<span>新增</span>
							</el-button>
							<!-- 添加数据弹框 -->
							<el-dialog v-model="addStudent" title="添加学生数据" width="440">
								<el-form :model="formadd">
									<el-form-item label="学号" :label-width="formaddWidth">
										<el-input
											v-model="formadd.studentNumber"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
									<el-form-item label="学生姓名" :label-width="formaddWidth">
										<el-input
											v-model="formadd.studentName"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
									<el-form-item label="性别" :label-width="formaddWidth">
										<el-select
											v-model="formadd.gender"
											placeholder="请选择性别"
											style="width: 260px"
										>
											<el-option label="男" value="男" />
											<el-option label="女" value="女" />
										</el-select>
									</el-form-item>
									<el-form-item label="年龄" :label-width="formaddWidth">
										<el-input
											v-model="formadd.age"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
									<el-form-item label="班级" :label-width="formaddWidth">
										<el-input
											v-model="formadd.className"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
									<el-form-item label="手机号" :label-width="formaddWidth">
										<el-input
											v-model="formadd.phoneNumber"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
								</el-form>
								<template #footer>
									<div class="dialog-footer">
										<el-button @click="addStudent = false">取消</el-button>
										<el-button type="primary" @click="addStudentData">
											确认
										</el-button>
									</div>
								</template>
							</el-dialog>
						</div>

						<!-- 表格 -->
						<div style="box-shadow: 1px 2px 10px #999; margin-top: 30px">
							<el-table :data="paginatedData" border style="width: 100%">
								<el-table-column prop="id" label="序号" width="100" />
								<el-table-column
									prop="studentNumber"
									label="学号"
									width="180"
								/>
								<el-table-column
									prop="studentName"
									label="学生姓名"
									width="150"
								/>
								<el-table-column prop="gender" label="性别" width="150" />
								<el-table-column prop="age" label="年龄" width="150" />
								<el-table-column prop="className" label="班级" width="230" />
								<el-table-column prop="phoneNumber" label="手机号" />
								<el-table-column fixed="right" label="操作" width="150">
									<template #default="scope">
										<el-button
											type="danger"
											:icon="Delete"
											circle
											plain
											@click="deleteStudent(scope.row.id)"
										/>
										<el-button
											type="primary"
											:icon="Edit"
											circle
											plain
											@click="updates(scope.row.id)"
										/>
									</template>
								</el-table-column>
							</el-table>
							<!-- 编辑数据弹框 -->
							<el-dialog
								v-model="updateStudent"
								title="编辑学生数据"
								width="440"
							>
								<el-form :model="formUpdate">
									<el-form-item label="学号" :label-width="formUpdateWidth">
										<el-input
											v-model="formUpdate.studentNumber"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
									<el-form-item label="学生姓名" :label-width="formUpdateWidth">
										<el-input
											v-model="formUpdate.studentName"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
									<el-form-item label="性别" :label-width="formUpdateWidth">
										<el-select
											v-model="formUpdate.gender"
											placeholder="请选择性别"
											style="width: 260px"
										>
											<el-option label="男" value="男" />
											<el-option label="女" value="女" />
										</el-select>
									</el-form-item>
									<el-form-item label="年龄" :label-width="formUpdateWidth">
										<el-input
											v-model="formUpdate.age"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
									<el-form-item label="班级" :label-width="formUpdateWidth">
										<el-input
											v-model="formUpdate.className"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
									<el-form-item label="手机号" :label-width="formUpdateWidth">
										<el-input
											v-model="formUpdate.phoneNumber"
											autocomplete="off"
											style="width: 260px"
										/>
									</el-form-item>
								</el-form>
								<template #footer>
									<div class="dialog-footer">
										<el-button @click="updateStudent = false">取消</el-button>
										<el-button type="primary" @click="comfirmUpdate">
											确认
										</el-button>
									</div>
								</template>
							</el-dialog>
						</div>
						<!-- 在表格下方添加分页组件 -->
						<el-config-provider :locale="locale">
							<el-pagination
								background
								v-model:current-page="currentPage"
								v-model:page-size="pageSize"
								:page-sizes="[5, 10, 15, 20]"
								:total="total"
								@size-change="handleSizeChange"
								@current-change="handleCurrentChange"
								layout="total, sizes, prev, pager, next, jumper"
								:locale="locale"
								class="pagination"
							/>
						</el-config-provider>
					</el-main>
					<!-- 版权 -->
					<el-footer class="footer">
						<span>© 2024 永恒帝宫. All rights reserved. </span>
					</el-footer>
				</el-container>
			</el-container>
		</el-container>
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { ArrowDown, Delete, Edit, Search } from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
const locale = zhCn
const std = ref('')
const studentName = ref('')
const router = useRouter() // 获取路由实例
function handleRegister() {
	// 使用 setTimeout 延迟 1 秒后跳转到登录页面
	setTimeout(() => {
		router.push('/login')
	}, 1000) // 延迟 1000 毫秒（1 秒）
	ElMessage(`退出登录成功`)
}
function handleChangePassword() {
	router.push('/changepassword')
}

// const menuItems = ['首页', '学生管理', '楼宇管理', '宿舍管理', '入住管理', '宿管管理', '管理员管理'];
// const menuItems = ref([
//     { name: '首页', path: '/' },
//     { name: '学生管理', path: '/studentmanage' },
//     { name: '宿舍管理', path: '/dormitorymanage' },
//     { name: '入住管理', path: '#' },
//     { name: '楼宇管理', path: '#' },
//     { name: '宿管管理', path: '#' },
//     { name: '管理员管理', path: '#' }
// ]);

// const activeIndex = ref(null);
// //点击更改样式
// function toggleBackgroundColor(index) {
//     activeIndex.value = index;
//     router.push(menuItems.value[index].path);
// }

//后端返回学生的json数据，用数组接收
const studentData = ref([])
//发送异步请求，获取学生数据
// 定义 fetchStudentData 函数以获取学生数据
const fetchStudentData = async () => {
	try {
		const response = await axios.get('http://localhost:8080/student', {
			params: {
				currentPage: currentPage.value,
				pageSize: pageSize.value
			}
		})
		studentData.value = response.data
	} catch (error) {
		console.error('获取学生数据失败: ', error)
	}
}
//在组件挂载时获取学生数据
onMounted(async () => {
	await fetchStudentData()
})

//查询学生数据
const search = async () => {
	try {
		//封装数据给前端
		const stdAndName = {
			studentNumber: std.value,
			studentName: studentName.value
		}
		const searchResponse = await axios.post(
			'http://localhost:8080/getStudentByStdName',
			stdAndName
		)
		//把查询到的数据渲染到页面中
		studentData.value = searchResponse.data
		//添加计数器，用于查询了多少条数据
		let count = 0
		for (let i = 0; i < studentData.value.length; i++) {
			count++
		}
		ElMessage({
			message: '查询成功，共查询了' + count + '条数据',
			type: 'success'
		})
	} catch {
		setTimeout(() => {
			ElMessage({
				message: '服务器未响应',
				type: 'warning'
			})
		}, 1000)
	}
}
//添加学生数据
const addStudent = ref(false)
const formaddWidth = '90px'
const formadd = reactive({
	studentNumber: '',
	studentName: '',
	gender: '',
	age: '',
	className: '',
	phoneNumber: ''
})

const addStudentData = async () => {
	try {
		//把学生数据封装到对象中
		const studentdata = {
			studentNumber: formadd.studentNumber,
			studentName: formadd.studentName,
			gender: formadd.gender,
			age: formadd.age,
			className: formadd.className,
			phoneNumber: formadd.phoneNumber
		}
		if (
			formadd.studentNumber == '' ||
			formadd.studentName == '' ||
			formadd.gender == '' ||
			formadd.age == '' ||
			formadd.className == '' ||
			formadd.phoneNumber == ''
		) {
			ElMessage({
				message: '请完善信息',
				type: 'warning',
				duration: 1000 // 设置消息显示时间为 1 秒
			})
			return
		}
		//点击确认关闭弹窗
		addStudent.value = false
		//发送数据给后端添加数据
		await axios.post('http://localhost:8080/insertStudentData', studentdata)
		//数据添加完初始化数据
		formadd.studentNumber = ''
		formadd.studentName = ''
		formadd.gender = ''
		formadd.age = ''
		formadd.className = ''
		formadd.phoneNumber = ''
		//修改成功后更新学生页面数据
		await fetchStudentData()
		ElMessage({
			message: '添加成功',
			type: 'success',
			duration: 1000 // 设置消息显示时间为 1 秒
		})
	} catch {
		setTimeout(() => {
			ElMessage({
				message: '服务器未响应',
				type: 'warning'
			})
		}, 1000) // 过1秒弹出服务器未响应
	}
}

//删除学生数据
const deleteStudent = studentId => {
	ElMessageBox.confirm('你确认要删除吗？', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		//发送异步请求到后端,根据id删除学生信息~
		try {
			await axios.delete(`http://localhost:8080/deleteStudent/${studentId}`)
			// 成功删除后更新页面数据
			// studentData.value = studentData.value.filter(student => student.id !== studentId);
			studentData.value = studentData.value.filter(
				(student: { id: number }) => student.id !== studentId
			)
			ElMessage({
				type: 'success',
				message: '删除成功',
				duration: 1000 // 设置消息显示时间为 1 秒
			})
		} catch {
			setTimeout(() => {
				ElMessage({
					type: 'warning',
					message: '服务器未响应'
				})
			}, 1000) // 过1秒弹出服务器未响应
		}
	})
}

// 更新学生数据
const updateStudent = ref(false)
const formUpdateWidth = '90px'
// const StudentDataList = ref([]);
const stdID = ref()
const formUpdate = reactive({
	studentNumber: '',
	studentName: '',
	gender: '',
	age: '',
	className: '',
	phoneNumber: ''
})

// 在 setup 函数中声明 StudentDataList 的类型
const StudentDataList = ref<
	{
		id: number
		studentNumber: string
		studentName: string
		gender: string
		age: string
		className: string
		phoneNumber: string
	}[]
>([])
const updates = async studentId => {
	//点击编辑按钮，弹出弹窗
	updateStudent.value = true
	try {
		//根据传递id，后端返回对应的值
		const Studentdata = await axios.get(
			`http://localhost:8080/getStudentsById?id=${studentId}`
		)
		StudentDataList.value = Studentdata.data
		//获取对应的id用于获取对应编辑内容，便于修改
		stdID.value = StudentDataList.value[0].id
		formUpdate.studentNumber = StudentDataList.value[0].studentNumber
		formUpdate.studentName = StudentDataList.value[0].studentName
		formUpdate.gender = StudentDataList.value[0].gender
		formUpdate.age = StudentDataList.value[0].age
		formUpdate.className = StudentDataList.value[0].className
		formUpdate.phoneNumber = StudentDataList.value[0].phoneNumber
	} catch {
		setTimeout(() => {
			ElMessage({
				message: '服务器未响应',
				type: 'warning'
			})
		}, 1000) // 过1秒弹出服务器未响应
	}
}

const comfirmUpdate = async () => {
	//点击确认关闭弹窗
	updateStudent.value = false
	//把学生数据封装到对象中
	const studentdata = {
		id: stdID.value,
		studentNumber: formUpdate.studentNumber,
		studentName: formUpdate.studentName,
		gender: formUpdate.gender,
		age: formUpdate.age,
		className: formUpdate.className,
		phoneNumber: formUpdate.phoneNumber
	}
	try {
		if (
			stdID.value == '' ||
			formUpdate.studentNumber == '' ||
			formUpdate.studentName == '' ||
			formUpdate.gender == '' ||
			formUpdate.age == '' ||
			formUpdate.className == '' ||
			formUpdate.phoneNumber == ''
		) {
			ElMessage({
				message: '修改失败',
				type: 'error',
				duration: 1000 // 设置消息显示时间为 1 秒
			})
			return
		}
		//把数据给到后端
		await axios.put('http://localhost:8080/updateStudent', studentdata)

		//修改成功后更新学生页面数据
		await fetchStudentData()
		ElMessage({
			message: '修改成功',
			type: 'success',
			duration: 1000 // 设置消息显示时间为 1 秒
		})
	} catch {
		setTimeout(() => {
			ElMessage({
				message: '服务器未响应',
				type: 'warning'
			})
		}, 1000) // 过1秒弹出服务器未响应
	}
}

// 分页相关的数据
const currentPage = ref(1)
const pageSize = ref(5)
const total = computed(() => studentData.value.length)

// 算当前页的数据
const paginatedData = computed(() => {
	const start = (currentPage.value - 1) * pageSize.value
	const end = start + pageSize.value
	return studentData.value.slice(start, end)
})

// 处理每页显示数量变化
const handleSizeChange = (val: number) => {
	pageSize.value = val
	currentPage.value = 1 // 重置到第一页
	fetchStudentData()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
	currentPage.value = val
	fetchStudentData()
}
</script>

<style scoped>
body {
	background-color: transparent;
}

html,
body {
	/* 移除默认的边距和填 */
	margin: 0;
	padding: 0;
	/* 确保页面高度少与视口度相同 */
	min-height: 100vh;
}

ul {
	margin: 0;
	padding: 0;
	text-align: center;
}

li {
	list-style: none;
}

.header {
	position: relative;
	background-color: #683b9e;
	font-size: 35px;
	height: 80px;
	line-height: 80px;
	color: #f9f1fa;
}

.aside {
	width: 200px;
	background-color: #8eb1c4;
}

ul li .a {
	height: 60px;
	line-height: 60px;
	display: block;
	text-decoration: none;
	font-size: 20px;
	width: 100%;
	color: black;
}

ul li .active {
	background-color: #044a8083;
	color: white;
}

ul li .a:hover {
	color: white;
}

.unlogin {
	text-decoration: none;
	color: #888;
}

.example-showcase .el-dropdown-link {
	cursor: pointer;
	color: var(--el-color-primary);
	display: flex;
	align-items: center;
}

.el-dropdown-link {
	position: relative;
	cursor: pointer;
	color: #fff;
}

.el-dropdown-link div {
	display: inline-block;
	width: 40px;
	height: 40px;
}

.position {
	position: absolute;
	top: 23px;
	right: 30px;
}

.footer {
	margin: 0;
	padding: 0;
	height: 50px;
	line-height: 50px;
	text-align: center;
	background-color: rgba(9, 218, 176, 0.404);
	color: #fff;
	border: 0;
}

.pagination-container {
	margin-top: 20px;
	padding: 10px 0;
	display: flex;
	justify-content: center;
}

.pagination {
	margin-top: 20px;
	display: flex;
	justify-content: flex-end;
}
</style>
